package com.egene.tw.activity.signs;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.egene.tw.R;
import com.egene.tw.base.BaseActivity;
import com.egene.tw.blue.BaseEvent;
import com.egene.tw.blue.BleEngine;
import com.egene.tw.blue.BluetoothLeServiceV2;
import com.egene.tw.blue.DataParser;
import com.egene.tw.data.DataRepository;
import com.egene.tw.data.RealmHelper;
import com.egene.tw.utils.PermissionUtils;
import com.weike.manager.CommandManager;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wzx on 2018/6/30.
 */

public class BaseMeasureActivity extends BaseActivity {
    protected CommandManager manager;
    private DataParser dataParser;

    public void initBle() {
        bleEngine = new BleEngine(this);
        bleEngine.initialize();


//        EventBus.getDefault().register(this);

        manager = CommandManager.getInstance(this);


        dataParser = DataParser.generate(manager, this);

        checkPAndStart();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case PermissionUtils.P_CODE_BLUE_TOOTH:
//                if (PermissionUtils.checkGrantResults(this, permissions)) {
////                    checkPAndStart();
//                }
//                break;
//        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PermissionUtils.P_CODE_BLUE_TOOTH:
                    checkPAndStart();
                    break;
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        connectAuto();
        //注册广播
//        LocalBroadcastManager.getInstance(this).registerReceiver(BLEStatusChangeReceiver, makeGattUpdateIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
//        stopScanBle();
//        LocalBroadcastManager.getInstance(this).unregisterReceiver(BLEStatusChangeReceiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dataParser.stopTransport();
//        EventBus.getDefault().unregister(this);
    }

//    private IntentFilter makeGattUpdateIntentFilter() {
//        final IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(BroadcastCommand.ACTION_DATA_AVAILABLE);
//        intentFilter.addAction(BroadcastCommand.ACTION_GATT_CONNECTED);
//        intentFilter.addAction(BroadcastCommand.ACTION_GATT_DISCONNECTED);
//        return intentFilter;
//    }

    private BleEngine bleEngine;

    public void checkPAndStart() {
        if (checkBT()) {
            BluetoothLeServiceV2.connectAuto(this);
        }
    }

    private void connectAuto() {
        if (PermissionUtils.checkHasPermission(this, PermissionUtils.PERMISSIONS_BLUE_TOOTH)
                && checkBTEnable()) {
            BluetoothLeServiceV2.connectAuto(this);
        }
    }

    public void stopScanBle() {
        BluetoothLeServiceV2.stopScan(this);
    }


    /**
     * 检查蓝牙
     */
    public boolean checkBT() {
        return checkBTPermission() && checkBTEnableAndOpen();
    }


    /**
     * 检查是否有权限，若无，则请求权限
     */
    public boolean checkBTPermission() {
        if (!PermissionUtils.checkHasPermission(this, PermissionUtils.PERMISSIONS_BLUE_TOOTH)) {
            PermissionUtils.requestPermissions(this, PermissionUtils.PERMISSIONS_BLUE_TOOTH, PermissionUtils.P_CODE_BLUE_TOOTH);
            return false;
        }
        return true;
    }

    public boolean checkBTEnable() {
        return bleEngine.checkBTEnable();
    }

    /**
     * 检查蓝牙功能是否打开，若未打开，则请求打开
     */
    public boolean checkBTEnableAndOpen() {
        if (!checkBTEnable()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, PermissionUtils.P_CODE_BLUE_TOOTH);
            return false;
        }
        return true;
    }


    public void onEventMainThread(BaseEvent baseEvent) {
        switch (baseEvent.getEventType()) {
            case BLUETOOTH_CONNECTED:
                Log.e("zgy", "BLUETOOTH_CONNECTED");
                break;
            case BLUETOOTH_DISCONNECTED:
                Log.e("zgy", "BLUETOOTH_DISCONNECTED");
                break;
            default:
                break;
        }
    }

//
//    public static String byteArrayToString(ArrayList<Byte> buffer) {
//        if (buffer == null) {
//            return "";
//        }
//        final StringBuilder stringBuilder = new StringBuilder(buffer.size());
//        if (buffer != null && buffer.size() > 0) {
//            for (byte byteChar : buffer) {
//                stringBuilder.append(String.format("%02X ", byteChar));
////                stringBuilder.append(String.format("%02X", byteChar));
////                stringBuilder.append("(" + byteChar + ") ");
//            }
//        }
//        return stringBuilder.toString();
//    }

    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////

    public void fangDiu(boolean off) {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        manager.antiLost(off ? 0 : 1);
    }

    public void remind(boolean off) {
//        if (!BluetoothLeServiceV2.connected) {
//            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
//            return false;
//        }
//        if (checkNotificationListenerEnable()) {
//            return true;
//        } else {
//            new AlertDialog.Builder(this)
//                    .setTitle("提示")
//                    .setMessage("智能提醒功能需要通知使用權，請前往設置。")
//                    .setPositiveButton("前往設置", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
//                            startActivityForResult(intent, 101);
//                        }
//                    })
//                    .setNegativeButton("取消", null)
//                    .show();
//            return false;
//        }
    }

    public void light(boolean off) {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        manager.upHandLightScreen(off ? 0 : 1);
    }

    public void dsMeasure(boolean off) {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        manager.onTimeMeasure(off ? 0 : 1);
    }

    public void clearData() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        manager.clearData();
        DataRepository.getInstance()
                .delAllData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Object o) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////
    public void measureSleep() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.sleep();
    }

    public void measureDropDown() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.dropDown();
    }

    public void findDevice() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.shake();
    }

    public void oneKeyMeasure() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.oneKeyMeasureStart();
    }

    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////
    public void heartOnce() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.heartOnceStart();
    }


    public void heartRT() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.heartRTStart();
    }

    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////
    public void oxygenOnce() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.oxygenOnceStart();
    }


    public void oxygenRT() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.oxygenRTStart();
    }


    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////
    public void bloodOnce() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.bloodOnceStart();
    }

    public void bloodRT() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        dataParser.bloodRTStart();
    }

    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////

    public boolean checkNotificationListenerEnable() {
        boolean enable = false;
        String packageName = getPackageName();
        String flat = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
        if (flat != null) {
            enable = flat.contains(packageName);
        }
        return enable;
    }
}
